package com.zoffy.oj_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoffy.oj_backend.common.ErrorCode;
import com.zoffy.oj_backend.exception.BusinessException;
import com.zoffy.oj_backend.mapper.UserMapper;


import com.zoffy.oj_backend.model.entity.User;

import com.zoffy.oj_backend.model.vo.UserVo;
import com.zoffy.oj_backend.service.UserService;

import com.zoffy.oj_backend.utils.OSSUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 86170
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private OSSUtils ossUtils;
    //session中保存登录态的字段
    private final String LOGIN_USER = "login_user";

    /**
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @param checkPassword 确定密码
     * @return 用户id
     */
    @Override
    public long userRegistry(String userAccount, String userPassword, String checkPassword) {
        //非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不全");
        }
        //账号密码长度校验
        if (userAccount.length() < 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号小于5位");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码小于8位");
        }
        //两次密码应该相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不相同");
        }
        //todo 账号中不存在敏感字符
        //检验账号是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = this.count(queryWrapper);
        if (count >= 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该账号已存在");
        }
        //创建账号
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(genSecret(userPassword));
        this.save(user);

        return user.getId();

    }

    @Override
    public UserVo userLogin(HttpServletRequest request, String userAccount, String userPassword) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不全");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", genSecret(userPassword));
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户名或密码错误");
        }
        UserVo userVo = convert2Vo(user);
        request.getSession().setAttribute(LOGIN_USER, userVo);
        return userVo;
    }


    public String genSecret(String secret) {
        String SALT = "zoffy_oj";
        return DigestUtils.md5DigestAsHex((SALT + secret).getBytes());
    }

    //获取当前登录的用户信息，如果未登录该方法会抛出异常
    @Override
    public UserVo currentUserVo(HttpServletRequest request) {
        UserVo userVo = (UserVo) request.getSession().getAttribute(LOGIN_USER);
        if (userVo == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User user = this.getById(userVo.getId());
        return convert2Vo(user);
    }

    @Override
    public boolean uploadAvatar(HttpServletRequest request, MultipartFile multipartFile) {
        UserVo userVo = currentUserVo(request);
        long userId = userVo.getId();
        String fileName = multipartFile.getName();
        //获取文件扩展名
        String[] strings = fileName.split("\\.");
        String ext;
        ext = strings.length == 1 ? "" : "." + strings[strings.length - 1];

        String uploadName = "userAvatar_" + userId + ext;
        try {
            return ossUtils.upload(multipartFile.getInputStream(), uploadName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    //将User转化为UserVo并补全其中完整的头像链接
    private UserVo convert2Vo(User user) {
        user.setUserAvatar(ossUtils.complementURL(user.getUserAvatar()));
        return UserVo.obj2Vo(user);
    }


}
